package com.pubsys.main.server.database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Helper class to aid the selection statement of DatabaseAdaptor.
 * This ensures that when making a selection the connection only stays opened
 * until the full data set is retrieved from a selection on the Database.
 * The selection statement is also stored in an instantiation of this class
 * @author Martin Reus
 *
 * @param <T> A returning class type for the data returned from the database
 */
public abstract class AbstractDataFetcher<T extends Object> {
	protected ArrayList<T> results = new ArrayList<T>();
	protected String sqlSelectionString = "";

	
	public AbstractDataFetcher(String sqlSelectionString) {
		this.sqlSelectionString = sqlSelectionString;
	}
	
	/**
	 * Has to be implemented by each instance. Provides a skeleton on
	 * how to fetch data from Database. Data retrieved should be stored inside
	 * <code>this.results</code> of type ArrayList<T>
	 * @param resultSet
	 * @throws SQLException 
	 */
	public abstract void fetchDataFromResultSet(ResultSet resultSet) throws SQLException;
	
	public final ArrayList<T> getFetchedData(){
		return results;
	}	
	
	public final void setSelectionString(String selectionString){
		this.sqlSelectionString = selectionString;
	}

	public final String getSelectionString(){
		return this.sqlSelectionString;
	}
	
	public final T getFirstOccurrence(){
		if (this.results.size() > 0)
			return this.results.get(0);
		else
			return null;
	}
}
